<!DOCTYPE html>
<html lang="zh-CN">





<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://img2.jimu98.cn/blog/20200729222712.png">
  <link rel="icon" type="image/png" href="https://img2.jimu98.cn/blog/20200729222712.png">
  <meta name="viewport"
        content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="description" content="你会的越多,你不会的越多,我是积木,互联网的一只小菜鸡">
  <meta name="author" content="积木">
  <meta name="keywords" content="积木,jimu98,java,后端,jimu">
  <title>【项目创建流程】Gateway微服务网关 - 积木 | 互联网的一只小菜鸡</title>

  <link  rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.staticfile.org/github-markdown-css/4.0.0/github-markdown.min.css" />
  <link  rel="stylesheet" href="/lib/hint/hint.min.css" />

  
    <link  rel="stylesheet" href="https://cdn.staticfile.org/highlight.js/10.0.0/styles/github-gist.min.css" />
  

  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_yg9cfy8wd6.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_pjno9b9zyxs.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script  src="/js/utils.js" ></script>
  <script data-ad-client="ca-pub-2806771379080352" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<meta name="generator" content="Hexo 4.2.1"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand"
       href="/">&nbsp;<strong>jimu98</strong>&nbsp;</a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/list/">
                <i class="iconfont icon-bookmark-fill"></i>
                导航
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" data-toggle="modal" data-target="#modalSearch">&nbsp;&nbsp;<i
                class="iconfont icon-search"></i>&nbsp;&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="view intro-2" id="background" parallax=true
         style="background: url('https://img2.jimu98.cn/blog/20200729222405.jpg') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="container text-center white-text fadeInUp">
            <span class="h2" id="subtitle">
              
            </span>

            
              
  <div class="mt-3 post-meta">
    <i class="iconfont icon-date-fill" aria-hidden="true"></i>
    <time datetime="2020-07-08 16:18">
      2020年7月8日 下午
    </time>
  </div>


<div class="mt-1">
  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      2.5k 字
    </span>
  

  
    
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      31
       分钟
    </span>
  

  
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid">
  <div class="row">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-md">
      <div class="container nopadding-md" id="board-ctn">
        <div class="py-5" id="board">
          <div class="post-content mx-auto" id="post">
            
            <article class="markdown-body">
              <h1 id="【项目创建流程】Gateway微服务网关"><a href="#【项目创建流程】Gateway微服务网关" class="headerlink" title="【项目创建流程】Gateway微服务网关"></a>【项目创建流程】Gateway微服务网关</h1><h2 id="网关基本概念"><a href="#网关基本概念" class="headerlink" title="网关基本概念"></a>网关基本概念</h2><h3 id="1、API网关介绍"><a href="#1、API网关介绍" class="headerlink" title="1、API网关介绍"></a>1、API网关介绍</h3><p>API 网关出现的原因是微服务架构的出现，不同的微服务一般会有不同的网络地址，而外部客户端可能需要调用多个服务的接口才能完成一个业务需求，如果让客户端直接与各个微服务通信，会有以下的问题：</p>
<p>（1）客户端会多次请求不同的微服务，增加了客户端的复杂性。</p>
<p>（2）存在跨域请求，在一定场景下处理相对复杂。</p>
<p>（3）认证复杂，每个服务都需要独立认证。</p>
<p>（4）难以重构，随着项目的迭代，可能需要重新划分微服务。例如，可能将多个服务合并成一个或者将一个服务拆分成多个。如果客户端直接与微服务通信，那么重构将会很难实施。</p>
<p>以上这些问题可以借助 API 网关解决。API 网关是介于客户端和服务器端之间的中间层，所有的外部请求都会先经过 API 网关这一层。也就是说，API 的实现方面更多的考虑业务逻辑，而安全、性能、监控可以交由 API 网关来做，这样既提高业务灵活性又不缺安全性</p>
<h3 id="2、Spring-Cloud-Gateway"><a href="#2、Spring-Cloud-Gateway" class="headerlink" title="2、Spring Cloud Gateway"></a>2、Spring Cloud Gateway</h3><p><strong>Spring cloud gateway</strong>是spring官方基于Spring 5.0和Spring Boot2.0等技术开发的网关，Spring Cloud Gateway旨在为微服务架构提供简单、有效和统一的API路由管理方式，Spring Cloud Gateway作为Spring Cloud生态系统中的网关，目标是替代Netflix Zuul，其不仅提供统一的路由方式，并且还基于Filer链的方式提供了网关基本的功能，例如：安全、监控/埋点、限流等。</p>
<h3 id="3、Spring-Cloud-Gateway-核心概念"><a href="#3、Spring-Cloud-Gateway-核心概念" class="headerlink" title="3、Spring Cloud Gateway 核心概念"></a>3、Spring Cloud Gateway 核心概念</h3><p>下面介绍一下Spring Cloud Gateway中几个重要的概念。</p>
<p>（1）路由。路由是网关最基础的部分，路由信息有一个ID、一个目的URL、一组断言和一组Filter组成。如果断言路由为真，则说明请求的URL和配置匹配</p>
<p>（2）断言。Java8中的断言函数。Spring Cloud Gateway中的断言函数允许开发者去定义匹配来自于http request中的任何信息，比如请求头和参数等。</p>
<p>（3）过滤器。一个标准的Spring webFilter。Spring cloud gateway中的filter分为两种类型的Filter，分别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理。</p>
<h3 id="4、执行流程"><a href="#4、执行流程" class="headerlink" title="4、执行流程"></a>4、执行流程</h3><p>如下图所示，Spring cloud Gateway发出请求。然后再由Gateway Handler Mapping中找到与请求相匹配的路由，将其发送到Gateway web handler。Handler再通过指定的过滤器链将请求发送到我们实际的服务执行业务逻辑，然后返回。</p>
<p><img src="https:////img2.jimu98.cn/blog/20200723154454.png" srcset="/img/loading.gif" alt="image-20200723154454083"></p>
<p><strong>4、特点</strong></p>
<p>优点：</p>
<ul>
<li>性能强劲：是第一代网关Zuul的1.6倍</li>
<li>功能强大：内置了很多实用的功能，例如转发、监控、限流等</li>
<li>设计优雅，容易扩展</li>
</ul>
<p>缺点：</p>
<ul>
<li>其实现依赖Netty与WebFlux，不是传统的Servlet编程模型，学习成本高</li>
<li>不能将其部署在Tomcat、Jetty等Servlet容器里，只能打成jar包执行</li>
<li>需要Spring Boot 2.0及以上的版本，才支持</li>
</ul>
<h2 id="搭建Gateway服务"><a href="#搭建Gateway服务" class="headerlink" title="搭建Gateway服务"></a>搭建Gateway服务</h2><h3 id="创建父模块infrastructure"><a href="#创建父模块infrastructure" class="headerlink" title="创建父模块infrastructure"></a>创建父模块infrastructure</h3><h3 id="创建子模块api-gateway"><a href="#创建子模块api-gateway" class="headerlink" title="创建子模块api_gateway"></a>创建子模块api_gateway</h3><h3 id="配置pom"><a href="#配置pom" class="headerlink" title="配置pom"></a>配置pom</h3><p>在api_gateway的pom中添加如下依赖</p>
<pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">dependencies</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- 网关 --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>org.springframework.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-gateway<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependencies</span>&gt;</span></code></pre>

<h3 id="配置application-yml"><a href="#配置application-yml" class="headerlink" title="配置application.yml"></a>配置application.yml</h3><pre><code class="hljs yaml"><span class="hljs-attr">server:</span>
  <span class="hljs-attr">port:</span> <span class="hljs-number">9110</span> <span class="hljs-comment"># 服务端口</span>

<span class="hljs-attr">spring:</span>
  <span class="hljs-attr">profiles:</span>
    <span class="hljs-attr">active:</span> <span class="hljs-string">dev</span> <span class="hljs-comment"># 环境设置</span>
  <span class="hljs-attr">application:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">infrastructure-apigateway</span> <span class="hljs-comment"># 服务名</span></code></pre>

<h3 id="logback-xml"><a href="#logback-xml" class="headerlink" title="logback.xml"></a>logback.xml</h3><p>修改日志输出目录名为 apigateway</p>
<h3 id="创建启动类"><a href="#创建启动类" class="headerlink" title="创建启动类"></a>创建启动类</h3><blockquote>
<p>gataway依赖common，课是common引入了mybatisplus操作，所有有数据库操作，因此需要排除数据库操作</p>
<p>@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class} )</p>
</blockquote>
<pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.guli.infrastructure.apigateway;

<span class="hljs-meta">@SpringBootApplication</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">InfrastructureApiGatewayApplication</span> </span>&#123;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>&#123;
        SpringApplication.run(InfrastructureApiGatewayApplication<span class="hljs-class">.<span class="hljs-keyword">class</span>, <span class="hljs-title">args</span>)</span>;
    &#125;
&#125;</code></pre>

<h2 id="启动网关"><a href="#启动网关" class="headerlink" title="启动网关"></a>启动网关</h2><h3 id="配置路由和跨域"><a href="#配置路由和跨域" class="headerlink" title="配置路由和跨域"></a>配置路由和跨域</h3><h4 id="1、路由和断言"><a href="#1、路由和断言" class="headerlink" title="1、路由和断言"></a>1、路由和断言</h4><p>application.yml文件中添加路由配置</p>
<ul>
<li>-：表示数组元素，可以配置多个节点</li>
<li>id：配置的唯一标识，可以和微服务同名，也可以起别的名字，区别于其他 Route。</li>
<li>uri：路由指向的目的地 uri，即客户端请求最终被转发到的微服务。</li>
<li>predicates：断言的作用是进行条件判断，只有断言都返回真，才会真正的执行路由。</li>
<li>Path：路径形式的断言。当匹配这个路径时，断言条件成立</li>
<li>/**：一个或多个层次的路径</li>
</ul>
<pre><code class="hljs dts"><span class="hljs-meta">#spring:</span>
<span class="hljs-symbol">  cloud:</span>
<span class="hljs-symbol">    gateway:</span>
<span class="hljs-symbol">      routes:</span>
      - id: service-edu
<span class="hljs-symbol">        uri:</span> http:<span class="hljs-comment">//localhost:8110</span>
<span class="hljs-symbol">        predicates:</span>
        - Path=<span class="hljs-meta-keyword">/user/</span>**</code></pre>

<h5 id="内置路由断言工厂"><a href="#内置路由断言工厂" class="headerlink" title="内置路由断言工厂"></a>内置路由断言工厂</h5><p>Predicate(断言) 用于进行条件判断，只有断言都返回真，才会真正的执行路由。</p>
<p>SpringCloud Gateway包括许多内置的断言工厂，所有这些断言都与HTTP请求的不同属性匹配。具体如下：</p>
<h6 id="1、基于Datetime"><a href="#1、基于Datetime" class="headerlink" title="1、基于Datetime"></a>1、基于Datetime</h6><p>此类型的断言根据时间做判断，主要有三个：</p>
<ul>
<li>AfterRoutePredicateFactory： 接收一个日期参数，判断请求日期是否晚于指定日期</li>
<li>BeforeRoutePredicateFactory： 接收一个日期参数，判断请求日期是否早于指定日期</li>
<li>BetweenRoutePredicateFactory： 接收两个日期参数，判断请求日期是否在指定时间段内</li>
</ul>
<pre><code class="hljs angelscript">- After=<span class="hljs-number">2019</span><span class="hljs-number">-12</span><span class="hljs-number">-31</span>T23:<span class="hljs-number">59</span>:<span class="hljs-number">59.789</span>+<span class="hljs-number">08</span>:<span class="hljs-number">00</span>[Asia/Shanghai]</code></pre>

<h6 id="2、基于远程地址"><a href="#2、基于远程地址" class="headerlink" title="2、基于远程地址"></a>2、基于远程地址</h6><p> RemoteAddrRoutePredicateFactory：接收一个IP地址段，判断请求主机地址是否在地址段中</p>
<pre><code class="hljs angelscript">- RemoteAddr=<span class="hljs-number">192.168</span><span class="hljs-number">.1</span><span class="hljs-number">.1</span>/<span class="hljs-number">24</span></code></pre>

<h6 id="3、基于Cookie"><a href="#3、基于Cookie" class="headerlink" title="3、基于Cookie"></a>3、基于Cookie</h6><p>CookieRoutePredicateFactory：接收两个参数，cookie 名字和一个正则表达式。 判断请求cookie是否具有给定名称且值与正则表达式匹配。</p>
<pre><code class="hljs routeros">- <span class="hljs-attribute">Cookie</span>=chocolate, ch.</code></pre>

<h6 id="4、基于Header"><a href="#4、基于Header" class="headerlink" title="4、基于Header"></a>4、基于Header</h6><p>HeaderRoutePredicateFactory：接收两个参数，标题名称和正则表达式。 判断请求Header是否具有给定名称且值与正则表达式匹配。</p>
<pre><code class="hljs routeros">- <span class="hljs-attribute">Header</span>=X-Request-Id, \d+</code></pre>

<h6 id="5、基于Host"><a href="#5、基于Host" class="headerlink" title="5、基于Host"></a>5、基于Host</h6><p>HostRoutePredicateFactory：接收一个参数，主机名模式。判断请求的Host是否满足匹配规则。</p>
<pre><code class="hljs routeros">- <span class="hljs-attribute">Host</span>=**.testhost.org</code></pre>

<h6 id="6、基于Method请求方法"><a href="#6、基于Method请求方法" class="headerlink" title="6、基于Method请求方法"></a>6、基于Method请求方法</h6><p>MethodRoutePredicateFactory：接收一个参数，判断请求类型是否跟指定的类型匹配。</p>
<pre><code class="hljs oxygene">- <span class="hljs-function"><span class="hljs-keyword">Method</span>=<span class="hljs-title">GET</span></span></code></pre>

<h6 id="7、基于Path请求路径"><a href="#7、基于Path请求路径" class="headerlink" title="7、基于Path请求路径"></a>7、基于Path请求路径</h6><p>PathRoutePredicateFactory：接收一个参数，判断请求的URI部分是否满足路径规则。</p>
<pre><code class="hljs haml">-<span class="ruby"> Path=<span class="hljs-regexp">/foo/</span>**</span></code></pre>

<h6 id="8、基于Query请求参数"><a href="#8、基于Query请求参数" class="headerlink" title="8、基于Query请求参数"></a>8、基于Query请求参数</h6><p>QueryRoutePredicateFactory ：接收两个参数，请求param和正则表达式， 判断请求参数是否具有给定名称且值与正则表达式匹配。</p>
<pre><code class="hljs routeros">- <span class="hljs-attribute">Query</span>=url,baidu</code></pre>

<h6 id="9、基于路由权重"><a href="#9、基于路由权重" class="headerlink" title="9、基于路由权重"></a>9、基于路由权重</h6><p>WeightRoutePredicateFactory：接收一个[组名,权重]，然后对于同一个组内的路由按照权重转发</p>
<pre><code class="hljs yaml"><span class="hljs-attr">routes:</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">id:</span> <span class="hljs-string">weight_route1</span> 
  <span class="hljs-attr">uri:</span> <span class="hljs-string">host1</span> 
  <span class="hljs-attr">predicates:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Path=/product/**</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Weight=group3,</span> <span class="hljs-number">1</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">id:</span> <span class="hljs-string">weight_route2</span> 
  <span class="hljs-attr">uri:</span> <span class="hljs-string">host2</span> 
  <span class="hljs-attr">predicates:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Path=/product/**</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Weight=</span> <span class="hljs-string">group3,</span> <span class="hljs-number">9</span></code></pre>

<h5 id="过滤器"><a href="#过滤器" class="headerlink" title="过滤器"></a>过滤器</h5><h6 id="一、过滤器的基本概念"><a href="#一、过滤器的基本概念" class="headerlink" title="一、过滤器的基本概念"></a>一、过滤器的基本概念</h6><p>1、作用</p>
<p>过滤器就是在请求的传递过程中，对请求和响应做一些修改</p>
<p>2、生命周期</p>
<p>客户端的请求先经过“pre”类型的filter，然后将请求转发到具体的业务服务，收到业务服务的响应之后，再经过“post”类型的filter处理，最后返回响应到客户端。</p>
<p>pre： 这种过滤器在请求被路由之前调用。我们可利用这种过滤器实现参数校验、权限校验、流量监控、日志输出、协议转换等；</p>
<p>post：这种过滤器在路由到达微服务以后执行。这种过滤器可用做响应内容、响应头的修改，日志的输出，流量监控等。</p>
<p><img src="https:////img2.jimu98.cn/blog/20200723154536.png" srcset="/img/loading.gif" alt="image-20200723154536196"></p>
<p>3、分类</p>
<p>局部过滤器 GatewayFilter：作用在某一个路由上</p>
<p>全局过滤器 GlobalFilter：作用全部路由上</p>
<h6 id="二、局部过滤器"><a href="#二、局部过滤器" class="headerlink" title="二、局部过滤器"></a>二、局部过滤器</h6><p>1、内置局部过滤器</p>
<p>在SpringCloud Gateway中内置了很多不同类型的网关路由过滤器。具体如下</p>
<pre><code class="hljs yaml"><span class="hljs-attr">routes:</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">id:</span> <span class="hljs-string">service-edu</span>
  <span class="hljs-attr">uri:</span> <span class="hljs-string">lb://service-edu</span>
  <span class="hljs-attr">predicates:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">Path=/user/**,</span> <span class="hljs-string">/*/edu/**</span>
  <span class="hljs-attr">filters:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">SetStatus=250</span> <span class="hljs-comment"># 修改返回状态码</span></code></pre>

<p>测试：</p>
<p><img src="https:////img2.jimu98.cn/blog/20200723154605.png" srcset="/img/loading.gif" alt="image-20200723154605180"></p>
<h6 id="三、全局过滤器"><a href="#三、全局过滤器" class="headerlink" title="三、全局过滤器"></a>三、全局过滤器</h6><p>1、内置全局过滤器</p>
<p><img src="https:////img2.jimu98.cn/blog/20200723154630.png" srcset="/img/loading.gif" alt="image-20200723154630370"></p>
<p>内置全局过滤器的使用举例：负载均衡过滤器</p>
<pre><code class="hljs dts"><span class="hljs-symbol">lb:</span><span class="hljs-comment">//service-edu</span></code></pre>

<p>2、自定义全局过滤器</p>
<p>定义一个Filter实现 GlobalFilter 和 Ordered接口</p>
<p><code>自定义转发路径</code></p>
<pre><code class="hljs yaml"><span class="hljs-attr">filters:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-string">RewritePath=/api/(?&lt;segment&gt;.*),/renren-fast/$\&#123;segment&#125;</span></code></pre>

<p>2、测试网关路由转发</p>
<p>访问：<a href="http://localhost:9110/user/info" target="_blank" rel="noopener">http://localhost:9110/user/info</a></p>
<p>请求转发到：<a href="http://localhost:9110/user/info" target="_blank" rel="noopener">http://localhost:8110/user/info</a></p>
<h3 id="通过nacos注册中心"><a href="#通过nacos注册中心" class="headerlink" title="通过nacos注册中心"></a>通过nacos注册中心</h3><h4 id="1、网关中添加依赖"><a href="#1、网关中添加依赖" class="headerlink" title="1、网关中添加依赖"></a>1、网关中添加依赖</h4><pre><code class="hljs xml"><span class="hljs-comment">&lt;!--服务注册--&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">dependency</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">groupId</span>&gt;</span>com.alibaba.cloud<span class="hljs-tag">&lt;/<span class="hljs-name">groupId</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">artifactId</span>&gt;</span>spring-cloud-starter-alibaba-nacos-discovery<span class="hljs-tag">&lt;/<span class="hljs-name">artifactId</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dependency</span>&gt;</span></code></pre>

<h4 id="2、主类添加注解"><a href="#2、主类添加注解" class="headerlink" title="2、主类添加注解"></a>2、主类添加注解</h4><pre><code class="hljs aspectj"><span class="hljs-meta">@EnableDiscoveryClient</span>  <span class="hljs-comment">//SpringBoot2.0之后可以省略</span></code></pre>

<h4 id="3、添加nacos配置"><a href="#3、添加nacos配置" class="headerlink" title="3、添加nacos配置"></a>3、添加nacos配置</h4><pre><code class="hljs yaml"><span class="hljs-comment">#spring:</span>
<span class="hljs-comment">#  cloud:</span>
    <span class="hljs-attr">nacos:</span>
      <span class="hljs-attr">discovery:</span>
        <span class="hljs-attr">server-addr:</span> <span class="hljs-string">localhost:8848</span> <span class="hljs-comment"># nacos服务地址</span></code></pre>

<h4 id="4、添加gateway配置"><a href="#4、添加gateway配置" class="headerlink" title="4、添加gateway配置"></a>4、添加gateway配置</h4><pre><code class="hljs yaml"><span class="hljs-comment">#spring:</span>
<span class="hljs-comment">#  cloud:</span>
<span class="hljs-comment">#    gateway:</span>
      <span class="hljs-attr">discovery:</span>
        <span class="hljs-attr">locator:</span>
          <span class="hljs-attr">enabled:</span> <span class="hljs-literal">true</span> <span class="hljs-comment"># gateway可以发现nacos中的微服务</span></code></pre>

<h4 id="5、修改uri配置"><a href="#5、修改uri配置" class="headerlink" title="5、修改uri配置"></a>5、修改uri配置</h4><p>将uri的地址修改成注册中心中的微服务地址，网关姜葱nacos中按照名称获取微服务</p>
<p>lb：表示在集群环境下通过负载均衡的方式调用</p>
<pre><code class="hljs groovy"><span class="hljs-string">uri:</span> <span class="hljs-string">lb:</span><span class="hljs-comment">//service-edu  #内置负载均衡过滤器</span></code></pre>

<h4 id="6、测试"><a href="#6、测试" class="headerlink" title="6、测试"></a>6、测试</h4><p>访问：<a href="http://localhost:9110/user/info" target="_blank" rel="noopener">http://localhost:9110/user/info</a></p>
<h4 id="7、匹配多个path"><a href="#7、匹配多个path" class="headerlink" title="7、匹配多个path"></a>7、匹配多个path</h4><pre><code class="hljs haml">-<span class="ruby"> Path=<span class="hljs-regexp">/user/</span>**, <span class="hljs-regexp">/*/edu</span><span class="hljs-regexp">/**</span></span></code></pre>

<h3 id="跨域配置"><a href="#跨域配置" class="headerlink" title="跨域配置"></a>跨域配置</h3><h4 id="1、前端配置"><a href="#1、前端配置" class="headerlink" title="1、前端配置"></a>1、前端配置</h4><p>修改guli-admin中 config/dev.env.js，BASE_API指定到网关地址</p>
<pre><code class="hljs 1c">BASE_API: '"http://127.0.0.1:<span class="hljs-number">9110</span>"',</code></pre>

<h4 id="2、删除后端跨域配置"><a href="#2、删除后端跨域配置" class="headerlink" title="2、删除后端跨域配置"></a>2、删除后端跨域配置</h4><p>此时可以删除微服务中的跨域注解 <em>@CrossOrigin</em></p>
<p><em>例如 service_edu中 LoginController的跨域注解</em></p>
<h4 id="3、跨域配置"><a href="#3、跨域配置" class="headerlink" title="3、跨域配置"></a>3、跨域配置</h4><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.atguigu.guli.infrastructure.apigateway.config;

<span class="hljs-meta">@Configuration</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CorsConfig</span> </span>&#123;
    <span class="hljs-meta">@Bean</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> CorsWebFilter <span class="hljs-title">corsFilter</span><span class="hljs-params">()</span> </span>&#123;
        CorsConfiguration config = <span class="hljs-keyword">new</span> CorsConfiguration();
        config.addAllowedMethod(<span class="hljs-string">"*"</span>);
        config.addAllowedOrigin(<span class="hljs-string">"*"</span>);
        config.addAllowedHeader(<span class="hljs-string">"*"</span>);

        UrlBasedCorsConfigurationSource source = <span class="hljs-keyword">new</span> UrlBasedCorsConfigurationSource(<span class="hljs-keyword">new</span> PathPatternParser());
        source.registerCorsConfiguration(<span class="hljs-string">"/**"</span>, config);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> CorsWebFilter(source);
    &#125;
&#125;</code></pre>

<p>注意：去掉后端的所有跨域配置</p>
<h3 id="完整的路由配置"><a href="#完整的路由配置" class="headerlink" title="完整的路由配置"></a>完整的路由配置</h3><h4 id="yml配置"><a href="#yml配置" class="headerlink" title="yml配置"></a>yml配置</h4><pre><code class="hljs haml">routes:
-<span class="ruby"> <span class="hljs-symbol">id:</span> service-edu</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-edu</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/user/</span>**, <span class="hljs-regexp">/*/edu</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-cms</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-cms</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/cms</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-oss</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-oss</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/oss</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-sms</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-sms</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/sms</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-trade</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-trade</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/trade</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-ucenter</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-ucenter</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/ucenter</span><span class="hljs-regexp">/**</span></span>
<span class="ruby">- <span class="hljs-symbol">id:</span> service-vod</span>
<span class="ruby">  <span class="hljs-symbol">uri:</span> <span class="hljs-symbol">lb:</span>/<span class="hljs-regexp">/service-vod</span></span>
<span class="ruby">  <span class="hljs-symbol">predicates:</span></span>
<span class="ruby">  - Path=<span class="hljs-regexp">/*/vod</span><span class="hljs-regexp">/**</span></span></code></pre>

<h4 id="前端配置"><a href="#前端配置" class="headerlink" title="前端配置"></a>前端配置</h4><p>（1）修改guli-site中 utils/request.js，BASE_API指定到网关地址</p>
<pre><code class="hljs 1c">baseURL: 'http://127.0.0.1:<span class="hljs-number">9110</span>',</code></pre>

<p>（2）所有的api模块中的baseURL可以删除</p>
<p>（3）guli-admin上传相关表单中action地址的修改</p>
<p>data中定义：</p>
<pre><code class="hljs css"><span class="hljs-selector-tag">BASE_API</span>: <span class="hljs-selector-tag">process</span><span class="hljs-selector-class">.env</span><span class="hljs-selector-class">.BASE_API</span></code></pre>

<p>html中使用：</p>
<pre><code class="hljs clojure"><span class="hljs-symbol">:action=</span><span class="hljs-string">"BASE_API+'/admin/oss/file/upload?module=avatar'"</span></code></pre>

<h2 id=""><a href="#" class="headerlink" title=""></a></h2>
            </article>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E9%A1%B9%E7%9B%AE%E6%9E%84%E5%BB%BA/">项目构建</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/SpringCloud/">SpringCloud</a>
                    
                      <a class="hover-with-bg" href="/tags/%E5%BE%AE%E6%9C%8D%E5%8A%A1/">微服务</a>
                    
                      <a class="hover-with-bg" href="/tags/Gateway/">Gateway</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" target="_blank" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！</p>
              
              
                <div class="post-prevnext row">
                  <div class="post-prev col-6">
                    
                    
                      <a href="/2020/07/10/jianzhi-offer/04.%E4%BA%8C%E7%BB%B4%E6%95%B0%E7%BB%84%E4%B8%AD%E7%9A%84%E6%9F%A5%E6%89%BE/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">【剑指Offer】二维数组中的查找</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </div>
                  <div class="post-next col-6">
                    
                    
                      <a href="/2020/07/08/goujian/11.%E6%95%B0%E6%8D%AE%E5%B1%95%E7%A4%BA%E5%92%8CRedis/">
                        <span class="hidden-mobile">【项目创建流程】集成Redis缓存</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </div>
                </div>
              
            </div>

            
              <!-- Comments -->
              <div class="comments" id="comments">
                
                
  <div id="vcomments"></div>
  <script type="text/javascript">
    function loadValine() {
      addScript('https://cdn.staticfile.org/valine/1.4.14/Valine.min.js', function () {
        new Valine({
          el: "#vcomments",
          app_id: "NFojgagn3zsFUjT0FGVVHUTM-gzGzoHsz",
          app_key: "9R1L32c7WEvSGSP48NAnfStY",
          placeholder: "说点什么",
          path: window.location.pathname,
          avatar: "retro",
          meta: ["nick","mail","link"],
          pageSize: "10",
          lang: "zh-CN",
          highlight: false,
          recordIP: true,
          serverURLs: "https://nfojgagn.lc-cn-n1-shared.com",
        });
      });
    }
    createObserver(loadValine, 'vcomments');
  </script>
  <noscript>Please enable JavaScript to view the <a href="https://valine.js.org" target="_blank" rel="nofollow noopener noopener">comments
      powered by Valine.</a></noscript>


              </div>
            
          </div>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div id="tocbot"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    
  </main>

  
    <a id="scroll-top-button" href="#" role="button">
      <i class="iconfont icon-arrowup" aria-hidden="true"></i>
    </a>
  

  
    <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
  

  

  

  <footer class="mt-5">
  <div class="text-center py-3">
  <p id="hitokoto">:D 获取中...</p>
<script>
  fetch('https://v1.hitokoto.cn')
    .then(response => response.json())
    .then(data => {
      const hitokoto = document.getElementById('hitokoto')
      hitokoto.innerText = data.hitokoto
      })
      .catch(console.error)
</script>
   <div>
  <span id="timeDate">载入天数...</span>
  <span id="times">载入时分秒...</span>
  <script>
  var now = new Date();
  function createtime(){
      var grt= new Date("07/18/2020 18:00:00");//此处修改你的建站时间或者网站上线时间
      now.setTime(now.getTime()+250);
      days = (now - grt ) / 1000 / 60 / 60 / 24;
      dnum = Math.floor(days);
      hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum);
      hnum = Math.floor(hours);
      if(String(hnum).length ==1 ){
          hnum = "0" + hnum;
      }
      minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
      mnum = Math.floor(minutes);
      if(String(mnum).length ==1 ){
                mnum = "0" + mnum;
      }
      seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
      snum = Math.round(seconds);
      if(String(snum).length ==1 ){
                snum = "0" + snum;
      }
      document.getElementById("timeDate").innerHTML = "本站安全运行&nbsp"+dnum+"&nbsp天";
      document.getElementById("times").innerHTML = hnum + "&nbsp小时&nbsp" + mnum + "&nbsp分&nbsp" + snum + "&nbsp秒";
  }
  setInterval("createtime()",250);
  </script>
</div>
    <div>
      &copy;2019 - 2020 By Jimu98
    </div>
    

    
  <!-- 备案信息 -->
  <div class="beian">
		
          <img src="/img/police_beian.png" srcset="/img/loading.gif" alt="police-icon" />
        
    <a href="http://beian.miit.gov.cn/" target="_blank"
       rel="nofollow noopener">冀ICP备19035627号</a>
    
  </div>


    
      <!-- cnzz Analytics Icon -->
      <span id="cnzz_stat_icon_1278280985" style="display: none"></span>
    
  </div>

</footer>

<!-- SCRIPTS -->
<script  src="https://cdn.staticfile.org/jquery/3.4.1/jquery.min.js" ></script>
<script  src="https://cdn.staticfile.org/twitter-bootstrap/4.4.1/js/bootstrap.min.js" ></script>
<script  src="/js/debouncer.js" ></script>
<script  src="/js/main.js" ></script>

<!-- Plugins -->


  
    <script  src="/js/lazyload.js" ></script>
  



  <script defer src="https://cdn.staticfile.org/clipboard.js/2.0.6/clipboard.min.js" ></script>
  <script  src="/js/clipboard-use.js" ></script>







  <script  src="https://cdn.staticfile.org/tocbot/4.11.1/tocbot.min.js" ></script>
  <script>
    $(document).ready(function () {
      var boardCtn = $('#board-ctn');
      var boardTop = boardCtn.offset().top;

      tocbot.init({
        tocSelector: '#tocbot',
        contentSelector: 'article.markdown-body',
        headingSelector: 'h1,h2,h3,h4,h5,h6',
        linkClass: 'tocbot-link',
        activeLinkClass: 'tocbot-active-link',
        listClass: 'tocbot-list',
        isCollapsedClass: 'tocbot-is-collapsed',
        collapsibleClass: 'tocbot-is-collapsible',
        collapseDepth: 0,
        scrollSmooth: true,
        headingsOffset: -boardTop
      });
      if ($('.toc-list-item').length > 0) {
        $('#toc').css('visibility', 'visible');
      }
    });
  </script>



  <script  src="https://cdn.staticfile.org/typed.js/2.0.11/typed.min.js" ></script>
  <script>
    var typed = new Typed('#subtitle', {
      strings: [
        '  ',
        "【项目创建流程】Gateway微服务网关&nbsp;",
      ],
      cursorChar: "|",
      typeSpeed: 95,
      loop: false,
    });
    typed.stop();
    $(document).ready(function () {
      $(".typed-cursor").addClass("h2");
      typed.start();
    });
  </script>



  <script  src="https://cdn.staticfile.org/anchor-js/4.2.2/anchor.min.js" ></script>
  <script>
    anchors.options = {
      placement: "right",
      visible: "hover",
      
    };
    var el = "h1,h2,h3,h4,h5,h6".split(",");
    var res = [];
    for (item of el) {
      res.push(".markdown-body > " + item)
    }
    anchors.add(res.join(", "))
  </script>



  <script  src="/js/local-search.js" ></script>
  <script>
    var path = "/local-search.xml";
    var inputArea = document.querySelector("#local-search-input");
    inputArea.onclick = function () {
      searchFunc(path, 'local-search-input', 'local-search-result');
      this.onclick = null
    }
  </script>



  <script  src="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.staticfile.org/fancybox/3.5.7/jquery.fancybox.min.css" />

  <script>
    $('#post img:not(.no-zoom img, img[no-zoom]), img[zoom]').each(
      function () {
        var element = document.createElement('a');
        $(element).attr('data-fancybox', 'images');
        $(element).attr('href', $(this).attr('src'));
        $(this).wrap(element);
      }
    );
  </script>







  
  
    <script>
      !function (e, t, a) {
        function r() {
          for (var e = 0; e < s.length; e++) s[e].alpha <= 0 ? (t.body.removeChild(s[e].el), s.splice(e, 1)) : (s[e].y--, s[e].scale += .004, s[e].alpha -= .013, s[e].el.style.cssText = "left:" + s[e].x + "px;top:" + s[e].y + "px;opacity:" + s[e].alpha + ";transform:scale(" + s[e].scale + "," + s[e].scale + ") rotate(45deg);background:" + s[e].color + ";z-index:99999");
          requestAnimationFrame(r)
        }

        function n() {
          var t = "function" == typeof e.onclick && e.onclick;
          e.onclick = function (e) {
            t && t(), o(e)
          }
        }

        function o(e) {
          var a = t.createElement("div");
          a.className = "heart", s.push({
            el: a,
            x: e.clientX - 5,
            y: e.clientY - 5,
            scale: 1,
            alpha: 1,
            color: c()
          }), t.body.appendChild(a)
        }

        function i(e) {
          var a = t.createElement("style");
          a.type = "text/css";
          try {
            a.appendChild(t.createTextNode(e))
          } catch (t) {
            a.styleSheet.cssText = e
          }
          t.getElementsByTagName("head")[0].appendChild(a)
        }

        function c() {
          return "rgb(" + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + "," + ~~(255 * Math.random()) + ")"
        }

        var s = [];
        e.requestAnimationFrame = e.requestAnimationFrame || e.webkitRequestAnimationFrame || e.mozRequestAnimationFrame || e.oRequestAnimationFrame || e.msRequestAnimationFrame || function (e) {
          setTimeout(e, 1e3 / 60)
        }, i(".heart{width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: fixed;}.heart:after{top: -5px;}.heart:before{left: -5px;}"), n(), r()
      }(window, document);
    </script>
  











  

  

  

  

  

  
    <!-- cnzz Analytics -->
    <script defer src="//s4.cnzz.com/z_stat.php?id=1278280985&show=pic"
            type="text/javascript"></script>
  





</body>
</html>
